<template>
  <a-modal v-model:visible="visible" centered title="打印二维码" :width="880" destroyOnClose>
    <a-steps v-model:current="currentStep">
      <a-step title="二维码设置" />
      <a-step title="打印布局设置" />
    </a-steps>
    <div v-show="firstStep" class="step-content-first">
      <qrcode-vue :value="qrUrl" :size="240" level="H" />
      <a-select
        style="width: 240px"
        placeholder="请选择"
        labelInValue
        :value="selectedValue"
        mode="multiple"
        allow-clear
        :options="computedColumnList"
        @change="handleChange"
      />
      <div>注：请选择展示字段，不选默认为空。</div>
    </div>
    <div v-show="secondStep" class="step-content-second">
      <div :class="['left', `paper-${onePaperNumber}`]">
        <div class="qr-wrapper" v-for="item in showQrCount" :key="item">
          <qrcode-vue :value="qrUrl" level="H" :size="qrWidth" />
          <div class="filed-content" v-show="selectedKeys.length">
            <div class="field" v-for="field in selectedLabel" :key="field">{{ field }}</div>
          </div>
        </div>
      </div>
      <div class="right">
        <div class="right-text">
          <b>A4纸布局设置</b>
          <p>注：仅支持A4纸打印</p>
        </div>
        <a-radio-group
          v-model:value="layoutRadioValue"
          :options="layoutOptions"
          style="margin-bottom: 25px"
        />
        <div>
          <b>打印分析</b>
          <p>当前已选 {{ selectedKeys.length }} 条数据，预计消耗 {{ paperNumber }} 张A4纸</p>
        </div>
      </div>
    </div>
    <template #footer>
      <a-button @click="handleCancel"> 取消 </a-button>
      <a-button type="primary" v-show="firstStep" @click="changeStep(1)"> 下一步 </a-button>
      <a-button type="primary" v-show="secondStep" @click="changeStep(0)"> 上一步 </a-button>
      <a-button type="primary" v-show="secondStep" @click="handlePrint" :loading="printLoading">
        立即打印
      </a-button>
    </template>
  </a-modal>
</template>

<script>
import QrcodeVue from 'qrcode.vue';
import { computed, defineComponent, ref } from 'vue';
import { message } from 'ant-design-vue';
import { fetchExportQr } from '@/apis/sys/form';
export default defineComponent({
  name: 'PrintModal',
  components: {
    QrcodeVue,
  },
  props: {
    columnList: {
      type: Array,
      default: () => [],
    },
    // 选中列
    selectedKeys: {
      type: Array,
      default: () => [],
    },
    dataSource: {
      type: Object,
      default: () => ({}),
    },
    applicationId: {
      type: Number,
    },
    pageId: {
      type: Number,
    },
  },
  setup(props) {
    const visible = ref(false);
    const currentStep = ref(0);
    const printLoading = ref(false);
    // 展示列名
    const selectedValue = ref([]);
    const selectedLabel = ref([]);
    const layoutOptions = [
      { label: '1×1', value: '1×1' },
      { label: '1×2', value: '1×2' },
      { label: '2×3', value: '2×3' },
      { label: '3×4', value: '3×4' },
    ];
    const layoutRadioValue = ref('1×1');
    const showModal = () => {
      currentStep.value = 0;
      selectedValue.value = [];
      visible.value = true;
    };
    const handleCancel = () => {
      visible.value = false;
    };

    const changeStep = (step) => {
      currentStep.value = step;
      if (step === 1) {
        layoutRadioValue.value = '1×1';
      }
    };

    const handlePrint = () => {
      const [x, y] = layoutRadioValue.value.split('×');
      const params = {
        applicationId: props.applicationId,
        pageId: props.pageId,
        pageDataIdList: props.selectedKeys,
        fieldList: selectedValue.value,
        horizontalCountPrePage: x,
        verticalCountPrePage: y,
      };
      fetchExportQr(params).then((res) => {
        if (res.data) {
          window.open(res.data);
        } else {
          message.destroy();
          message.error('生成PDF失败');
        }
      });
    };

    const computedColumnList = computed(() => {
      return props.columnList
        .filter(
          (item) =>
            !['sequenceNumber', 'operation', 'qrcode'].includes(item.dataIndex) &&
            !item?.children.length,
        )
        .map((item) => ({
          value: item.dataIndex,
          label: item.title,
        }));
    });
    const qrUrl = computed(() => {
      const firstSelect = props.dataSource.find((item) => item.id === props.selectedKeys[0]);
      if (firstSelect?.qrCodeUrl) {
        return firstSelect.qrCodeUrl;
      }
      return '';
    });
    const firstStep = computed(() => currentStep.value === 0);
    const secondStep = computed(() => currentStep.value === 1);

    const handleChange = (options) => {
      if (options.length >= 3) {
        message.destroy();
        message.warn('最多选择2个标签');
        return;
      }
      selectedValue.value = options.map((item) => item.value);
      selectedLabel.value = options.map((item) => item.label);
    };
    // 布局乘得到的积
    const onePaperNumber = computed(() => {
      const [x, y] = layoutRadioValue.value.split('×');
      return x * y;
    });
    // 需要展示的二维码数量
    const showQrCount = computed(() => {
      if (props.selectedKeys.length <= onePaperNumber.value) {
        return props.selectedKeys.length;
      }
      return onePaperNumber.value;
    });
    // 消耗的纸张数
    const paperNumber = computed(() => {
      if (props.selectedKeys.length <= onePaperNumber.value) {
        return 1;
      } else if (props.selectedKeys.length % onePaperNumber.value === 0) {
        return parseInt(props.selectedKeys.length / onePaperNumber.value);
      } else {
        return parseInt(props.selectedKeys.length / onePaperNumber.value) + 1;
      }
    });

    const qrWidth = computed(() => {
      const qrWidthMap = {
        '1×1': 180,
        '1×2': 100,
        '2×3': 60,
        '3×4': 45,
      };
      return qrWidthMap[layoutRadioValue.value];
    });


    return {
      qrWidth,
      onePaperNumber,
      showQrCount,
      paperNumber,
      handleChange,
      selectedValue,
      firstStep,
      secondStep,
      visible,
      currentStep,
      printLoading,
      showModal,
      handleCancel,
      changeStep,
      handlePrint,
      computedColumnList,
      qrUrl,
      layoutOptions,
      layoutRadioValue,
      selectedLabel,
    };
  },
});
</script>

<style lang="less" scoped>
.step-content-first {
  height: 340px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}
.step-content-second {
  width: 100%;
  height: 340px;
  display: flex;
  justify-content: center;
  align-items: center;
  .left {
    width: 250px;
    height: 355px;
    border: 1px solid #e8e8e8;
    margin-right: 50px;
    padding: 10px;
    .filed-content {
      width: 100%;
      text-align: center;
      line-height: 1.1;
      & > * {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        word-break: keep-all;
      }
    }
  }
  .qr-wrapper {
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    align-items: center;
  }

  .paper-1 {
    display: flex;
    justify-content: center;
    align-items: center;
    .qr-wrapper {
      width: 180px;
      height: 255px;
    }
    .filed-content {
      font-size: 20px;
      margin-top: 10px;
    }
  }
  .paper-2 {
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    flex-direction: column;
    .qr-wrapper {
      width: 150px;
      height: 180px;
    }
    .filed-content {
      font-size: 16px;
      margin-top: 4px;
    }
  }
  .paper-6 {
    display: flex;
    align-content: flex-start;
    flex-wrap: wrap;
    gap: 5px;
    .qr-wrapper {
      width: 100px;
      height: 109px;
    }
  }
  .paper-12 {
    display: flex;
    align-content: flex-start;
    flex-wrap: wrap;
    gap: 8px;
    .filed-content {
      font-size: 12px;
      margin-top: 5px;
    }
    .qr-wrapper {
      width: 70px;
      height: 78px;
    }
  }
  .one-qr-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    .qr-wrapper {
      display: flex;
      flex-direction: column;
    }
  }
}
</style>
